package chat;

import java.awt.*;
import java.awt.event.*;


public class UserDialogPrivateMessageAWT extends Frame
{
    private UserDialogAWT zUserDialog;
    private MyInfo zMyInfo;
    private ActivePeer zPeerListener;

    private TextField zChatText;
    private TextArea zMessagesTextArea;

    public UserDialogPrivateMessageAWT( UserDialogAWT pUserDialog , MyInfo pMyInfo , ActivePeer pPeerListener )
    {
        super( "P2P Chat Private Messaging with " + pPeerListener.getPeerInfo().toString() );

        IllegalArgument.ifNull( "UserDialog" , zUserDialog = pUserDialog );
        IllegalArgument.ifNull( "MyInfo" , zMyInfo = pMyInfo );
        IllegalArgument.ifNull( "PeerListener" , zPeerListener = pPeerListener );

        setLayout( new BorderLayout() );

        add( "Center" , layoutReceivedMessagesPanel() );
        add( "South" , layoutChatEntryPanel() );
        pack();
        addWindowListener(
            new WindowAdapter()
            {
                public void windowClosing( WindowEvent e )
                {
                    zUserDialog.unregisterPrivateMessager( zPeerListener.getPeerInfo() );
                    dispose();
                }
            }
        );
        show();
    }

    private Panel layoutChatEntryPanel()
    {
        Panel panel = new Panel();
        panel.setLayout( new BorderLayout() );
        panel.add( "West" , new Label( "Message to Send:" ) );
        panel.add( "Center" , zChatText = new TextField() );
        zChatText.addActionListener(
            new ActionListener()
            {
                public void actionPerformed( ActionEvent e )
                {
                    String pLine = e.getActionCommand();
                    zChatText.setText( "" );
                    zPeerListener.sendPMSG( pLine );
                    send( zMyInfo.getChatName() + ": " + pLine );
                }
            }
        );
        return panel;
    }

    private Panel layoutReceivedMessagesPanel()
    {
        Panel panel = new Panel();
        panel.setLayout( new BorderLayout() );
        panel.add( "North" , new Label( "Received Messages:" ) );
        panel.add( "Center" , zMessagesTextArea = new TextArea() );
        zMessagesTextArea.setEnabled( true );
        zMessagesTextArea.setEditable( false );
        return panel;
    }

    public void send( String pMessage )
    {
        IllegalArgument.ifNull( "Message" , pMessage );
        String current = zMessagesTextArea.getText();
        current += pMessage + "\n";
        zMessagesTextArea.setText( current );
    }
}
